package ymos.mytracker.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import ymos.mytracker.dao.TrackerDao;
import ymos.mytracker.exception.ServerInfoExcption;
import ymos.mytracker.json.ServInfo;
import ymos.mytracker.object.ServerInfoDb;
import ymos.mytracker.utli.GetPlayerList;
import ymos.mytracker.utli.GetServerInfo;
import ymos.mytracker.utli.ServerInfo;
@Service
public class GetInfoServiceImpl implements GetInfoService{
	@Autowired
	TrackerDao dao;
	@Override
	public ServInfo getInfo(String ip, Integer port) throws ServerInfoExcption {
		ServerInfoDb db = dao.findByAddress(ip, port);
		if(db==null) throw new ServerInfoExcption("ip未提交");
		ServInfo info = new ServInfo();
		Long time = db.getTimestemp();
		ServerInfoDb cachedb = new ServerInfoDb(); 
		if(time==null) {
			submitServer(ip,port,cachedb);
		}else if((System.currentTimeMillis()-time)>1000*60){
			submitServer(ip,port,cachedb);
		}
		if(cachedb.getServername()!=null) {
			cachedb.setIp(ip);
			cachedb.setPort(port);
			dao.updateByAddress(cachedb);
			db=cachedb;
		}else if(db.getServername()==null) {
			throw new ServerInfoExcption("请等待新刷..");
		}
		info.setIp(ip);
		info.setPort(port);
		info.setServername(db.getServername());
		info.setMap(db.getMap());
		info.setPlayers(db.getPlayers());
		info.setMaxplayer(db.getMaxplayer());
		
		String str = db.getPlayerlist();
		if(str!=null) {
			String[] players=str.split(",");
			List<String> list = new ArrayList<String>();
			for(String s:players) {
				list.add(s);
			}
			info.setPlayerlist(list);
		}
		return info;
	}
	
	private void submitServer(String ip,Integer port,ServerInfoDb server) {
		try {
			ServerInfo info = GetServerInfo.connect(ip, port);
			server.setMap(info.getMap());
			server.setServername(info.getServerName());
			server.setMaxplayer(info.getMaxPlayer());
			server.setPlayers(info.getMinPlayer());
			int ran = new Random().nextInt(1000*5)+5000;
			server.setTimestemp(System.currentTimeMillis()-ran);
			StringBuilder str = new StringBuilder();
			List<String> list = GetPlayerList.connect(ip, port);
			if(list!=null) {
				String fix = list.size()==1?"":",";
				for(String s:list) {
					if(s.matches("^[\\u4e00-\\u9fa5_a-zA-Z0-9]+$")) {
						str.append(s+fix);
					}
				}
				server.setPlayerlist(str.toString());
			}
		} catch (IOException e) {
			server.setServername(null);
		}
	}

}
